package Server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class UserServer {
    public static void createServerSocket() throws IOException {
        final ReentrantLock lock = new ReentrantLock();
        List<Socket> list = new ArrayList<>();//客户端连接Socket
        Map<Socket, String> map = new HashMap<>();//socket---用户名
        ServerSocket server = new ServerSocket(9000);
        System.out.println("服务器开启，等待用户连接");
        while (true) {

            //服务器开启多线程
            final Socket socket = server.accept();

            //服务器获取用户名
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String userName = br.readLine();
            //System.out.println("获取到了用户名"+userName);

            //添加客户端
            lock.lock();
            list.add(socket);
            lock.unlock();

            //添加客户端的用户名
            lock.lock();
            map.put(socket, userName);//用户名加入
            lock.unlock();

            //开启线程
            new Thread(new ServerThread(socket, list, map)).start();
        }
    }

    static class ServerThread implements Runnable {
        private final Socket socket;
        private final List<Socket> list;
        private final Map<Socket, String> map;


        public ServerThread(Socket socket, List<Socket> list, Map<Socket, String> map) {
            this.socket = socket;
            this.list = list;
            this.map = map;
        }

        @Override
        public void run() {
            final ReentrantLock lock = new ReentrantLock();
            System.out.println("客户端已连接!");
            InputStream is;
            try {

                is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));

                sendUsers();//发送给所有用户
                lock.lock();
                String str = "";
                while ((str = br.readLine()) != null) {
                    if (!str.equals("\n")) {
                        sendUsersTOAll(str);
                        System.out.println(str);
                    }
                }

            } catch (IOException e) {
                list.remove(socket);
                map.remove(socket);
                sendUsers();//更新用户
            } finally {
                lock.unlock();
                sendUsers();//更新用户
            }
        }

        private void sendUsers() {
            String users = null;
            List<String> userList = new ArrayList<String>(map.values());
            //有客户时发送
            if (!userList.isEmpty()) {
                users = "USER_START" + "\n";
                for (String user : userList)
                    users += user + "\n";
                users = users + "USER_END" + "\n";
            }
            sendUsersTOAll(users);
        }

        private void sendUsersTOAll(String str) {

            for (Socket s : list) {
                try {
                    //System.out.println("sendUsersTOALL有用！");
                    PrintStream ps = new PrintStream(s.getOutputStream());
                    boolean flag = true;
                    while (flag) {

                        flag = false;
                    }
                    ps.println(str);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



